package com.njit.office.controller;

import com.njit.office.dataobject.LoginUser;
import com.njit.office.form.AddInformForm;
import com.njit.office.form.CreateTeamForm;
import com.njit.office.form.JoinTeamForm;
import com.njit.office.model.*;
import com.njit.office.service.*;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Controller
public class PageController {

    @Resource
    RedisService redisService;

    @Resource
    UserService userService;

    @Resource
    TeamService teamService;

    @Resource
    InformService informService;

    @Resource
    TaskService taskService;

    @GetMapping("/")
    public ModelAndView index(HttpServletRequest request, Model model) {
        //表示已经登录，获取session中的相关id,查询信息
        if (!hasSession(request)) {
            return new ModelAndView("index");
        }

        String userId = getUserId(request);
        LoginUser loginUser = userService.getUserWithId(userId);
        model.addAttribute("user", loginUser);
        model.addAttribute("userForm", new LoginUser());
        return new ModelAndView("main", "userModel", model);
    }

    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result result = new Result();
        if(hasSession(request)){
            //删除session和cookie
            String userId = getUserId(request);
            redisService.delete("loginUser:" + userId);
            HttpSession session = request.getSession();
            session.removeAttribute("userId");
            session.invalidate();
        }
        result.setSuccess(true);
        return result;
    }

    @GetMapping("/index")
    public String index() {
        return "/index";
    }

    @GetMapping("/team")
    public ModelAndView team(HttpServletRequest request, Model model) {
        if (!hasSession(request)) {
            return new ModelAndView("team");
        }
        String userId = getUserId(request);
        Result res1 = teamService.getJoinedTeams(userId);
        Result res2 = teamService.getCreatedTeams(userId);
        if (res1.isSuccess()&&res2.isSuccess()) {
            model.addAttribute("joinedTeams", res1.getData());
            model.addAttribute("createdTeams", res2.getData());
            model.addAttribute("userId", userId);
            model.addAttribute("createTeamForm", new CreateTeamForm());
            model.addAttribute("joinTeamForm", new JoinTeamForm());
            return new ModelAndView("team", "teamModel",model);
        }
        return new ModelAndView("team");
    }

    @GetMapping("chat")
    public String chat() {
        return "chat";
    }

    @GetMapping("file")
    public String file() {
        return "file";
    }

    @GetMapping("message")
    public String message() {
        return "message";
    }

    @GetMapping("task")
    public ModelAndView task(HttpServletRequest request, Model model) {
        if (!hasSession(request)) {
            return new ModelAndView("task");
        }
        String userId = getUserId(request);
        Result task = taskService.getTask(userId);
        List<TaskModel> taskModels = (List<TaskModel>) task.getData();

        //过滤正在进行并且不是紧急的任务
        List<TaskModel> doingTasks = taskModels.stream().filter(new Predicate<TaskModel>() {
            @Override
            public boolean test(TaskModel taskModel) {
                return taskModel.getTaskState().equals(TaskState.UNFINISHED)&&!taskModel.isUrgent();
            }
        }).collect(Collectors.toList());

        //过滤紧急的任务
        List<TaskModel> urgentTasks = taskModels.stream().filter(new Predicate<TaskModel>() {
            @Override
            public boolean test(TaskModel taskModel) {
                return taskModel.getTaskState().equals(TaskState.UNFINISHED)&&taskModel.isUrgent();
            }
        }).collect(Collectors.toList());

        //过滤已完成的任务
        List<TaskModel> finishedTasks = taskModels.stream().filter(new Predicate<TaskModel>() {
            @Override
            public boolean test(TaskModel taskModel) {
                return taskModel.getTaskState().equals(TaskState.FINISHED);
            }
        }).collect(Collectors.toList());

        Result res1 = teamService.getCreatedTeams(userId);
        model.addAttribute("addTaskForm", new AddInformForm());
        model.addAttribute("doingTasks",doingTasks);
        model.addAttribute("urgentTasks", urgentTasks);
        model.addAttribute("finishedTasks",finishedTasks);
        model.addAttribute("createdTeams", res1.getData());
        return new ModelAndView("task","taskModel",model);
    }

    @GetMapping("inform")
    public ModelAndView inform(HttpServletRequest request,Model model) {
        if (!hasSession(request)) {
            return new ModelAndView("inform");
        }
        String userId = getUserId(request);
        Result res1 = informService.getUnReadInform(userId);
        Result res2 = informService.getUnDoInform(userId);
        Result res3 = informService.getFinishedInform(userId);
        Result res4 = teamService.getCreatedTeams(userId);
        Result res5 = informService.getFinishedInform(userId);
        if (res1.isSuccess()&&res2.isSuccess()&&res3.isSuccess()) {
            model.addAttribute("unReadInforms",InformController.sortInforms((List<InformModel>) res1.getData()));
            model.addAttribute("unDoInforms",InformController.sortInforms((List<InformModel>) res2.getData()));
            model.addAttribute("userId", userId);
            model.addAttribute("addInformForm", new AddInformForm());
            model.addAttribute("createdTeams", res4.getData());
            model.addAttribute("finishedInforms", InformController.sortInforms((List<InformModel>) res5.getData()));
            return new ModelAndView("inform", "informModel",model);
        }
        return new ModelAndView("inform");
    }


    private boolean hasSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session == null || session.getAttribute("userId") == null) {
            return false;
        }
        return true;
    }

    private String getUserId(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return (String) session.getAttribute("userId");
    }


}
